from select_query_node import *
from table_query_node import *
from join_query_node import *
from condition_query_node import *

class QueryTreeBuilder:
	'''
		builde mmrsql query tree according to parse result from yacc
	'''

	def __init__(self):
		pass
	
	def build_query_tree(self, query_parse_dict):
		"""
			build a query tree according to query_parse_dict (which contains key 'select_list', 'talbe_list' and 'condition_list')
		"""
		select_list = query_parse_dict['select_list']
		table_list = query_parse_dict['table_list']
		condition_list = query_parse_dict['condition_list']

		select_node = SelectQueryNode(select_list)
		condition_node = ConditionQueryNode(condition_list)
		join_root_node = self.build_join_tree(table_list)		

		condition_node.child_node_list.append(join_root_node)
		select_node.child_node_list.append(condition_node)
		self.print_query_tree(select_node, 0)
		return select_node

	def build_join_tree(self, table_list):
		'''
			turn table_list ([t1, t2, [c11, c12], t3, [c21, c22], ...]) into
						 
						  |
					 [c21, c22]
					/		   \
				[c11, c12]		t3
			   /		  \
			t1				t2

			return root_node
		'''
		if len(table_list) % 2 == 0 :
			print 'build join tree():table_list num error'
			return None
		tmp_list = []		#contains tree leaf
		for item in table_list:
			if not isinstance(item, list):
				table_node = TableQueryNode(item)
				tmp_list.append(table_node)
			else:
				arg = {'condition_dict': item}
				join_node = JoinQueryNode(condition_list=item)
				join_node.child_node_list.extend(tmp_list)
				del(tmp_list[:])
				tmp_list.append(join_node)

		cur_root_node = tmp_list[0]
		return cur_root_node

	def print_query_tree(self, root_node, depth):
		print '\t'*depth, root_node
		for child_node in root_node.child_node_list:
			self.print_query_tree(child_node, depth+1)

if __name__ == '__main__':
	builder = QueryTreeBuilder()
	root_node = builder.build_join_tree(['t1', 't2', ['c11', 'c12'], 't3', ['c21', 'c22']])
	builder.print_join_tree(root_node, 0)

